<template>
  <div class="report-process-container">
    <div class="page-header">
      <el-page-header @back="goBack" content="举报处理详情" />
    </div>

    <el-card class="report-card">
      <template #header>
        <div class="card-header">
          <span>举报信息</span>
        </div>
      </template>

      <el-descriptions :column="1" border>
        <el-descriptions-item label="举报单号">{{ report.reportId }}</el-descriptions-item>
        <el-descriptions-item label="举报人ID">{{ report.reporterId }}</el-descriptions-item>
        <el-descriptions-item label="举报人昵称">{{ report.nickname }}</el-descriptions-item>
        <el-descriptions-item label="举报类型">{{ report.reportType }}</el-descriptions-item>
        <el-descriptions-item label="举报内容">{{ report.reason }}</el-descriptions-item>
        <el-descriptions-item label="举报时间">{{ report.createdAt }}</el-descriptions-item>
        <el-descriptions-item label="当前状态">
          <el-tag :type="report.status === 'pending' ? 'warning' : 'success'">
            {{ report.status === 'pending' ? '待处理' : '已处理' }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 举报视频展示卡片 -->
    <el-card class="videos-card">
      <template #header>
        <div class="card-header">
          <span>举报视频</span>
        </div>
      </template>

      <div class="videos-container">
        <div v-for="video in reportVideos" :key="video.reportVideoId" class="video-item">
          <el-card class="video-card" shadow="hover">
            <template #header>
              <div class="video-card-header">
                <span class="video-title">视频证据 {{ video.reportVideoId }}</span>
                <el-tag type="info" size="small">{{ formatVideoTime(video.createdAt) }}</el-tag>
              </div>
            </template>

            <div class="video-content">
              <div class="video-wrapper">
                <video
                  controls
                  preload="metadata"
                  class="video-player"
                  @error="handleVideoError"
                  :key="video.reportVideoId"
                >
                  <source :src="getVideoUrl(video.videoUrl)" type="video/mp4">
                  您的浏览器不支持视频播放。
                </video>
              </div>
            </div>

            <div class="video-actions">
              <el-button
                type="primary"
                link
                @click="downloadVideo(getVideoUrl(video.videoUrl))"
                :icon="Download"
                size="small"
              >
                下载
              </el-button>
              <el-button
                type="primary"
                link
                @click="previewVideo(getVideoUrl(video.videoUrl))"
                :icon="View"
                size="small"
              >
                预览
              </el-button>
            </div>
          </el-card>
        </div>

        <!-- 当没有视频时显示占位符 -->
        <div v-if="reportVideos.length === 0" class="video-placeholder">
          <el-empty description="暂无视频证据" :image-size="80">
            <template #image>
              <div class="placeholder-icon-wrapper">
                <el-icon class="placeholder-icon"><VideoCamera /></el-icon>
              </div>
            </template>
          </el-empty>
        </div>
      </div>
    </el-card>

    <el-card class="processing-card">
      <template #header>
        <div class="card-header">
          <span>处理信息</span>
        </div>
      </template>

      <el-form :model="processingForm" label-width="100px" class="processing-form">
        <el-form-item label="处理结果">
          <el-input
            v-model="processingForm.processingResult"
            type="textarea"
            :rows="4"
            placeholder="请输入处理结果描述"
          />
        </el-form-item>

        <el-form-item label="处理状态">
          <el-radio-group v-model="processingForm.status">
            <el-radio label="pending">待处理</el-radio>
            <el-radio label="processed">已处理</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="updateProcessing">保存处理结果</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 视频预览对话框 -->
    <el-dialog
      v-model="videoPreviewVisible"
      title="视频预览"
      width="600px"
      destroy-on-close
    >
      <div class="video-preview-container">
        <div class="video-preview-wrapper" v-if="previewVideoUrl">
          <video
            controls
            preload="auto"
            class="video-preview-player"
            @error="handlePreviewVideoError"
            :key="previewVideoUrl"
          >
            <source :src="previewVideoUrl" type="video/mp4">
            您的浏览器不支持视频播放。
          </video>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="videoPreviewVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { VideoCamera, Download, View } from '@element-plus/icons-vue'
import axios from 'axios'
import routers from "@/router";

const route = useRoute()
const router = useRouter()

// 举报数据
const report = ref({
  reportId: '',
  reporterId: '',
  nickname: '',
  reportType: '',
  reason: '',
  createdAt: '',
  status: 'pending'
})

// 处理表单数据
const processingForm = ref({
  processingResult: '',
  status: 'pending'
})

// 处理记录数据
const reportProcessing = ref({
  processingId: null,
  reportId: null,
  processingResult: '',
  createdAt: null,
  processedAt: null,
  status: 'pending'
})

// 举报视频数据
const reportVideos = ref([])

// 视频预览相关
const videoPreviewVisible = ref(false)
const previewVideoUrl = ref('')

// 格式化日期为后端需要的格式
const formatDateTime = (date) => {
  if (!date) return null
  // 如果是字符串且已经是正确格式，直接返回
  if (typeof date === 'string' && date.includes(' ')) {
    return date
  }
  // 如果是Date对象或其他格式，转换为 yyyy-MM-dd HH:mm:ss 格式
  const d = new Date(date)
  if (isNaN(d.getTime())) return null

  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')
  const seconds = String(d.getSeconds()).padStart(2, '0')

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 格式化视频时间显示
const formatVideoTime = (date) => {
  if (!date) return ''
  const d = new Date(date)
  if (isNaN(d.getTime())) return ''

  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')

  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 处理视频URL，确保正确的路径
const getVideoUrl = (videoUrl) => {
  // 如果URL包含 /video/report/ 路径，说明是public目录下的视频
  if (videoUrl && videoUrl.includes('/video/report/')) {
    // 直接使用相对路径访问public目录下的视频
    return videoUrl;
  }

  // 如果是其他路径，添加BASE_URL前缀
  if (videoUrl && videoUrl.startsWith('/')) {
    return BASE_URL + videoUrl;
  }

  // 其他情况直接返回
  return videoUrl || '';
}

// 处理视频加载错误
const handleVideoError = (event) => {
  console.error('视频加载失败:', event.target.src);
  ElMessage.warning('视频加载失败，请检查视频文件是否存在');
}

// 处理预览视频加载错误
const handlePreviewVideoError = (event) => {
  console.error('预览视频加载失败:', event.target.src);
  ElMessage.warning('预览视频加载失败，请检查视频文件是否存在');
}

// 下载视频
const downloadVideo = (videoUrl) => {
  const link = document.createElement('a');
  link.href = videoUrl;
  link.download = videoUrl.split('/').pop() || 'video.mp4';
  link.click();
}

// 预览视频
const previewVideo = (videoUrl) => {
  previewVideoUrl.value = videoUrl;
  videoPreviewVisible.value = true;
}

// 获取举报处理信息
const getReportProcessing = () => {
  const reportId = route.query.reportId
  if (!reportId) return

  axios.get(BASE_URL + `/api/reports/processing/select/report/${reportId}`)
    .then(response => {
      if (response.data.state === 2001) {
        const processing = response.data.data
        reportProcessing.value = processing
        processingForm.value.processingResult = processing.processingResult || ''
        // 处理状态需要从report_processing表中获取
        processingForm.value.status = processing.status || 'pending'
      } else {
        // 如果没有处理记录，则创建一个新的
        reportProcessing.value.reportId = parseInt(reportId)
        processingForm.value.status = 'pending'
      }
    })
    .catch(error => {
      console.error('获取处理信息失败:', error)
      ElMessage.error('获取处理信息失败: ' + (error.message || '网络错误'))
    })
}

// 获取举报视频
const getReportVideos = () => {
  const reportId = route.query.reportId
  if (!reportId) return

  // 修改这里的URL路径，使用新的report路径
  axios.get(BASE_URL + `/api/report-videos/select/report/${reportId}`)
      .then(response => {
        if (response.data.state === 2001) {
          reportVideos.value = response.data.data || []
        } else {
          ElMessage.error(response.data.msg || '获取举报视频失败')
        }
      })
      .catch(error => {
        console.error('获取举报视频失败:', error)
        ElMessage.error('获取举报视频失败: ' + (error.message || '网络错误'))
      })
}

// 更新处理信息
const updateProcessing = () => {
  // 格式化日期
  const createdAtFormatted = reportProcessing.value.createdAt || formatDateTime(new Date())
  const processedAtFormatted = processingForm.value.status === 'processed'
    ? formatDateTime(new Date())
    : null

  // 构建处理数据
  const processingData = {
    processingId: reportProcessing.value.processingId,
    reportId: parseInt(route.query.reportId),
    processingResult: processingForm.value.processingResult,
    createdAt: createdAtFormatted,
    processedAt: processedAtFormatted,
    status: processingForm.value.status
  }

  if (reportProcessing.value.processingId) {
    // 更新处理记录
    axios.put(BASE_URL + `/api/reports/processing/update`, processingData)
      .then(response => {
        if (response.data.state === 2001) {
          ElMessage.success('处理信息更新成功')
          // 更新本地举报状态
          report.value.status = processingForm.value.status
          routers.push('/report')
        } else {
          ElMessage.error(response.data.msg || '更新处理信息失败')
        }
      })
      .catch(error => {
        console.error('更新处理信息失败:', error)
        ElMessage.error('更新处理信息失败: ' + (error.message || '网络错误'))
      })
  } else {
    // 添加处理记录
    axios.post(BASE_URL + `/api/reports/processing/add`, processingData)
      .then(response => {
        if (response.data.state === 2001) {
          ElMessage.success('处理信息添加成功')
          // 更新本地举报状态
          report.value.status = processingForm.value.status
          // 重新获取处理信息以获取新ID
          getReportProcessing()
        } else {
          ElMessage.error(response.data.msg || '添加处理信息失败')
        }
      })
      .catch(error => {
        console.error('添加处理信息失败:', error)
        ElMessage.error('添加处理信息失败: ' + (error.message || '网络错误'))
      })
  }
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 初始化数据
onMounted(() => {
  // 从路由参数获取举报信息
  report.value = {
    reportId: route.query.reportId || '',
    reporterId: route.query.reporterId || '',
    nickname: route.query.nickname || '',
    reportType: route.query.reportType || '',
    reason: route.query.reason || '',
    createdAt: route.query.createdAt || '',
    status: route.query.status || 'pending'
  }

  // 获取处理信息
  getReportProcessing()

  // 获取举报视频
  getReportVideos()
})
</script>

<style scoped>
.report-process-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
  padding: 16px 24px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  font-weight: 600;
  color: #303133;
  font-size: 18px;
}

.report-card,
.videos-card,
.processing-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.processing-form {
  padding: 20px 0;
}

.videos-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  padding: 10px 0;
}

.video-item {
  flex: 1 1 calc(50% - 10px);
  min-width: 300px;
}

.video-card {
  border-radius: 8px;
  border: 1px solid #ebeef5;
  transition: all 0.3s ease;
}

.video-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.video-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.video-title {
  font-weight: 500;
  color: #303133;
  font-size: 14px;
}

.video-content {
  padding: 15px 0;
}

.video-wrapper {
  position: relative;
  width: 100%;
  padding-top: 56.25%; /* 16:9 宽高比 */
  border-radius: 4px;
  overflow: hidden;
  background-color: #000;
}

.video-player {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.video-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 10px;
  border-top: 1px solid #ebeef5;
}

.video-placeholder {
  flex: 1 1 100%;
  min-height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.placeholder-icon-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background-color: #f2f6fc;
  margin: 0 auto 10px;
}

.placeholder-icon {
  font-size: 36px;
  color: #c0c4cc;
  width: 1em;
  height: 1em;
}

.video-preview-container {
  text-align: center;
}

.video-preview-wrapper {
  position: relative;
  width: 100%;
  padding-top: 56.25%; /* 16:9 宽高比 */
  border-radius: 4px;
  overflow: hidden;
  background-color: #000;
}

.video-preview-player {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

:deep(.el-descriptions__label) {
  font-weight: 500;
  width: 100px !important;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-textarea__inner) {
  border-radius: 6px;
}

:deep(.el-button) {
  border-radius: 6px;
  transition: all 0.3s ease;
}

:deep(.el-button:hover) {
  transform: translateY(-1px);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

:deep(.el-empty__image) {
  margin-bottom: 0;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

@media (max-width: 768px) {
  .video-item {
    flex: 1 1 100%;
  }

  .video-preview-wrapper {
    padding-top: 75%; /* 4:3 宽高比 for mobile */
  }

  .report-process-container {
    padding: 15px;
  }

  :deep(.el-card__body) {
    padding: 15px;
  }
}
</style>
